#include "s3c2440_reg.h"

void nand_init(void);
void nand_reset(void);
void nand_enable(void);
void nand_disable(void);
unsigned int nand_read_data(void);
void nand_copyto_sdram(unsigned long start_addr, unsigned char * dest_addr, unsigned int size);
void nand_send_cmmd(unsigned char cmmd);
void nand_send_addr(unsigned int addr);
void nand_wait_idle(void);

void nand_init(void)
{
	NFCONF = (11<<12)|(111<<8)|(111<<4); /*set time*/
	//NFCONF &= (~1); /*set bus width*/
	//NFCONT &= (~1); /*enalbe nand controller*/
	NFCONT = (1<<1)|(1<<4)|(1<<0);
	nand_reset();
}

void nand_reset(void)
{
	nand_enable();
	nand_send_cmmd(0xff);
	nand_wait_idle();
	nand_disable();
}

void nand_enable(void)
{
	int i;
	NFCONT &= ~(1<<1);/*nand flash chip enable*/
	for(i=0; i<100; i++);
}

void nand_disable(void)
{
	NFCONT |= (1<<1);
}

void nand_send_cmmd(unsigned char cmmd)
{
	int i;
	NFCMMD = cmmd;
	for(i=0; i<100; i++);
}

void nand_send_addr(unsigned int addr)
{
	int i;
	NFADDR = addr & 0xff;
	for(i=0; i<100; i++);
	NFADDR = (addr>>8) & 0xf;   /*column address*/
	for(i=0; i<100; i++);
	NFADDR = (addr>>12) & 0xff;
	for(i=0; i<100; i++);
	NFADDR = (addr>>20) & 0xff;
	for(i=0; i<100; i++);
	NFADDR = (addr>>28) & 0x1;   /*row address*/
	for(i=0; i<100; i++);
}

unsigned int nand_read_data(void)
{
	int i;
	return NFDATA;
	for(i=0; i<100; i++);
}

void nand_wait_idle(void)
{
	int i;
	while(!(NFSTAT & 1))
	{
		for(i=0; i<100; i++);
	}
}

void nand_copyto_sdram(unsigned long start_addr, unsigned char * dest_addr, unsigned int size)
{
	int i;
	int j;
	nand_enable();
	for(i=start_addr;i<(start_addr+size);i=i+2048)
	{
		nand_send_cmmd(0x00);
		nand_send_addr(i);
		nand_send_cmmd(0x30);
		nand_wait_idle();
		for(j=0;j<2048;j++)
		{
			*dest_addr = (nand_read_data()&0xff);
			dest_addr++;
		}
	}
	nand_disable();
}


